import { getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
import store from '@/store';
import { DialogConfig, DialogFormItem } from '@/store/dialog';

@Module({ name: 'drawer', dynamic: true, namespaced: true, store })
export default class DrawerStore extends VuexModule {
    private _info = {} as DialogConfig;
    private _form: {[key: string]: DialogFormItem[]} = {};
    private _data = {} as { [key: string]: any };
    private _visible: boolean = false;

    public get visible(): boolean {
        return this._visible;
    }

    public get info(): DialogConfig {
        return this._info;
    }

    public get form(): DialogFormItem[] {
        let list: any[] = [];
        for (let formKey in this._form) {
            if (formKey === this._info.type) {
                list = this._form[formKey];
                break;
            } else if (formKey.indexOf('|') > -1) {
                const tmps = formKey.split('|');
                if (tmps.indexOf(this._info.type) > -1) {
                    list = this._form[formKey];
                    break;
                }
            }
        }

        return list;
    }

    public get data(): { [key: string]: any } {
        return this._data ?? {};
    }

    /**
     * 打开新窗体
     * title 窗体标题
     * url 接口地址
     * type 窗体类型
     * callback 提交回调，参数为接口返回数据
     * data 窗体表单默认数据
     * @param data
     */
    @Mutation
    public open(data: DialogConfig) {
        this._info = {
            ...data,
        };
        if (data.form) {
            this._form = data.form;
        }
        this._data = { ...data.data };
        this._visible = true;
    }

    /**
     * 执行回调
     * @param data
     */
    @Mutation
    public callback(data: any) {
        this._info.callback(data);
    }

    @Mutation
    public setValue({ key, value }: { key: string, value: any }) {
        if (!this._data) {
            this._data = {};
        }
        this._data = {
            ...this._data,
            [key]: value,
        }
        console.log('wewe', key, this._data)
    }

    /**
     * 关闭窗体
     */
    @Mutation
    public close() {
        this._visible = false;
    }

    /**
     * 销毁当前窗体数据
     */
    @Mutation
    public dispose() {
        this._info = {} as any;
        this._form = {} as any;
        this._data = {} as any;
    }
}

export const DrawerModule = getModule(DrawerStore);
